<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>用户管理系统</title>
    <!-- 引入 jQuery -->
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <style>
        /* 全局样式重置 */
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: "Microsoft YaHei", sans-serif;
            background-color: #f8f9fa;
            color: #333;
            line-height: 1.6;
            min-height: 100vh;
        }

        /* 容器和标题样式 */
        .container {
            max-width: 1400px;
            margin: 0 auto;
            padding: 20px;
        }

        .title {
            font-size: 24px;
            font-weight: bold;
            margin-bottom: 20px;
            color: #333;
        }

        /* 搜索和添加区域样式 */
        .search-add-bar {
            display: flex;
            flex-wrap: wrap;
            gap: 10px;
            justify-content: space-between;
            align-items: center;
            margin-bottom: 20px;
        }

        .search-group {
            display: flex;
            flex: 1;
            max-width: 500px;
        }

        .search-group input {
            flex: 1;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px 0 0 4px;
            outline: none;
            font-size: 14px;
        }

        .search-group button {
            padding: 10px 16px;
            background-color: #00b359;
            color: #fff;
            border: none;
            border-radius: 0 4px 4px 0;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .search-group button:hover {
            background-color: #00994c;
        }

        .add-btn {
            padding: 10px 16px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .add-btn:hover {
            background-color: #0056b3;
        }

        /* 表格样式 */
        .table-container {
            overflow-x: auto;
        }

        .table {
            width: 100%;
            border-collapse: collapse;
            background-color: #fff;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.05);
        }

        .table th,
        .table td {
            padding: 12px 15px;
            text-align: center;
            border: 1px solid #ddd;
        }

        .table th {
            background-color: #f5f5f5;
            font-weight: 600;
            color: #333;
            text-transform: uppercase;
            font-size: 14px;
        }

        .table tbody tr:nth-child(even) {
            background-color: #f9f9fa;
        }

        .table tbody tr:hover {
            background-color: #f1f1f1;
            transition: background-color 0.2s;
        }

        /* 操作按钮样式 */
        .operate-btn {
            padding: 8px 12px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            margin: 0 3px;
            color: #fff;
            font-size: 14px;
            transition: all 0.2s;
        }

        .edit {
            background-color: #00b359;
        }

        .delete {
            background-color: #dc3545;
        }

        .operate-btn:hover {
            transform: translateY(-1px);
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
        }

        .edit:hover {
            background-color: #00994c;
        }

        .delete:hover {
            background-color: #c82333;
        }

        /* 模态框样式 */
        .modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 1000;
            justify-content: center;
            align-items: center;
            padding: 20px;
        }

        .modal-content {
            background-color: #fff;
            border-radius: 8px;
            box-shadow: 0 5px 20px rgba(0, 0, 0, 0.1);
            max-width: 500px;
            width: 100%;
            position: relative;
            animation: fadeIn 0.3s ease-out;
        }

        .modal-header {
            padding: 15px 20px;
            border-bottom: 1px solid #eee;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .modal-header h2 {
            font-size: 18px;
            font-weight: 600;
            color: #333;
        }

        .close-modal {
            font-size: 20px;
            color: #666;
            cursor: pointer;
            background: none;
            border: none;
        }

        .close-modal:hover {
            color: #333;
        }

        .modal-body {
            padding: 20px;
        }

        .form-group {
            margin-bottom: 15px;
        }

        .form-group label {
            display: block;
            margin-bottom: 5px;
            font-weight: 500;
            color: #555;
        }

        .form-group input {
            width: 100%;
            padding: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 14px;
            outline: none;
        }

        .form-group input:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 2px rgba(0, 123, 255, 0.25);
        }

        .modal-footer {
            padding: 15px 20px;
            border-top: 1px solid #eee;
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .modal-btn {
            padding: 10px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            transition: background-color 0.3s;
        }

        .save {
            background-color: #28a745;
            color: #fff;
        }

        .save:hover {
            background-color: #218838;
        }

        .cancel {
            background-color: #6c757d;
            color: #fff;
        }

        .cancel:hover {
            background-color: #5a6268;
        }

        /* 空数据提示样式 */
        .empty-data {
            padding: 50px 20px;
            text-align: center;
            color: #888;
        }

        /* 加载动画样式 */
        .loading {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.8);
            z-index: 1001;
            justify-content: center;
            align-items: center;
        }

        .loading-spinner {
            border: 4px solid #f3f3f3;
            border-top: 4px solid #007bff;
            border-radius: 50%;
            width: 30px;
            height: 30px;
            animation: spin 1s linear infinite;
        }

        /* 动画效果 */
        @keyframes fadeIn {
            from { opacity: 0; transform: scale(0.95); }
            to { opacity: 1; transform: scale(1); }
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        /* 响应式设计 */
        @media (max-width: 768px) {
            .search-add-bar {
                flex-direction: column;
                align-items: stretch;
            }

            .search-group {
                max-width: none;
            }

            .add-btn {
                width: 100%;
                justify-content: center;
            }

            .table th,
            .table td {
                padding: 8px 10px;
                font-size: 13px;
            }

            .operate-btn {
                padding: 6px 8px;
                font-size: 12px;
            }

            .modal-content {
                max-width: 100%;
            }
        }
    </style>
</head>
<body>
<div class="container">
    <div class="title">用户管理系统</div>

    <!-- 搜索 + 添加按钮区域 -->
    <div class="search-add-bar">
        <div class="search-group">
            <input type="text" id="searchInput" placeholder="请输入用户名搜索...">
            <button id="searchBtn">查询</button>
        </div>
        <button class="add-btn" id="addUserBtn">添加用户</button>
    </div>

    <!-- 表格容器 -->
    <div class="table-container">
        <table class="table" id="userTable">
            <thead>
            <tr>
                <th>用户ID</th>
                <th>用户名</th>
                <th>身份证号</th>
                <th>邮箱</th>
                <th>联系电话</th>
                <th>居住地址</th>
                <th>操作</th>
            </tr>
            </thead>
            <tbody>
            <!-- 数据通过 AJAX 渲染 -->
            </tbody>
        </table>
    </div>
</div>

<!-- 添加用户模态框 -->
<div class="modal" id="addModal">
    <div class="modal-content">
        <div class="modal-header">
            <h2>添加用户</h2>
            <button class="close-modal" id="closeAddModal">&times;</button>
        </div>
        <div class="modal-body">
            <div class="form-group">
                <label for="addUserName">用户名：</label>
                <input type="text" id="addUserName" placeholder="请输入用户名">
            </div>
            <div class="form-group">
                <label for="addPid">身份证号：</label>
                <input type="text" id="addPid" placeholder="请输入身份证号">
            </div>
            <div class="form-group">
                <label for="addEmail">邮箱：</label>
                <input type="text" id="addEmail" placeholder="请输入邮箱">
            </div>
            <div class="form-group">
                <label for="addMobile">联系电话：</label>
                <input type="text" id="addMobile" placeholder="请输入联系电话">
            </div>
            <div class="form-group">
                <label for="addAddress">居住地址：</label>
                <input type="text" id="addAddress" placeholder="请输入居住地址">
            </div>
            <div class="form-group">
                <label for="addPassword">密码：</label>
                <input type="password" id="addPassword" placeholder="请输入密码">
            </div>
        </div>
        <div class="modal-footer">
            <button class="modal-btn cancel" id="cancelAdd">取消</button>
            <button class="modal-btn save" id="saveAddUser">保存</button>
        </div>
    </div>
</div>

<!-- 编辑用户模态框 -->
<div class="modal" id="editModal">
    <div class="modal-content">
        <div class="modal-header">
            <h2>编辑用户</h2>
            <button class="close-modal" id="closeEditModal">&times;</button>
        </div>
        <div class="modal-body">
            <input type="hidden" id="editUserId">
            <div class="form-group">
                <label for="editUserName">用户名：</label>
                <input type="text" id="editUserName" placeholder="请输入用户名">
            </div>
            <div class="form-group">
                <label for="editPid">身份证号：</label>
                <input type="text" id="editPid" placeholder="请输入身份证号">
            </div>
            <div class="form-group">
                <label for="editEmail">邮箱：</label>
                <input type="text" id="editEmail" placeholder="请输入邮箱">
            </div>
            <div class="form-group">
                <label for="editMobile">联系电话：</label>
                <input type="text" id="editMobile" placeholder="请输入联系电话">
            </div>
            <div class="form-group">
                <label for="editAddress">居住地址：</label>
                <input type="text" id="editAddress" placeholder="请输入居住地址">
            </div>
            <div class="form-group">
                <label for="editPassword">密码：</label>
                <input type="password" id="editPassword" placeholder="请输入密码">
            </div>
        </div>
        <div class="modal-footer">
            <button class="modal-btn cancel" id="cancelEdit">取消</button>
            <button class="modal-btn save" id="saveEditUser">保存</button>
        </div>
    </div>
</div>

<!-- 删除确认模态框 -->
<div class="modal" id="deleteModal">
    <div class="modal-content">
        <div class="modal-header">
            <h2>确认删除</h2>
            <button class="close-modal" id="closeDeleteModal">&times;</button>
        </div>
        <div class="modal-body">
            <input type="hidden" id="deleteUserId">
            <div class="text-center">
                <p>您确定要删除该用户吗？此操作不可撤销。</p>
            </div>
        </div>
        <div class="modal-footer">
            <button class="modal-btn cancel" id="cancelDelete">取消</button>
            <button class="modal-btn save" id="confirmDelete">确认删除</button>
        </div>
    </div>
</div>

<!-- 加载动画 -->
<div class="loading" id="loading">
    <div class="loading-spinner"></div>
</div>

<script>
    // 接口基础路径（根据实际后端地址调整）
    const baseUrl = "/sysUser";

    // 页面加载时获取所有用户
    $(document).ready(function() {
        showLoading();
        loadUsers();
        hideLoading();

        // 查询按钮点击事件
        $("#searchBtn").click(function() {
            const searchName = $("#searchInput").val().trim();
            showLoading();
            loadUsers(searchName);
            hideLoading();
        });

        // 回车键触发查询
        $("#searchInput").keypress(function(e) {
            if (e.which === 13) {
                const searchName = $(this).val().trim();
                showLoading();
                loadUsers(searchName);
                hideLoading();
            }
        });

        // 添加用户按钮点击事件
        $("#addUserBtn").click(function() {
            openModal("addModal");
        });

        // 关闭添加模态框
        $("#closeAddModal, #cancelAdd").click(function() {
            closeModal("addModal");
            resetAddForm();
        });

        // 保存添加用户
        $("#saveAddUser").click(function() {
            if (!validateAddForm()) return;

            const user = {
                userName: $("#addUserName").val().trim(),
                pid: $("#addPid").val().trim(),
                email: $("#addEmail").val().trim(),
                mobile: $("#addMobile").val().trim(),
                address: $("#addAddress").val().trim(),
                password: $("#addPassword").val().trim()
            };

            showLoading();
            // 调用添加接口
            $.ajax({
                url: baseUrl + "/save",
                type: "POST",
                contentType: "application/json",
                data: JSON.stringify(user),
                success: function(res) {
                    if (res.success) {
                        alert("添加成功！");
                        closeModal("addModal");
                        resetAddForm();
                        loadUsers();
                    } else {
                        alert("添加失败：" + res.message);
                    }
                },
                error: function(err) {
                    alert("服务器错误：" + err.responseText);
                },
                complete: function() {
                    hideLoading();
                }
            });
        });

        // 修改后（使用getUser接口）
        $("#userTable").on("click", ".edit", function() {
            const userId = $(this).data("id");
            showLoading();

            // 调用查询接口（假设后端路径为 /sysUser/getUser/{userId}）
            $.ajax({
                url: baseUrl + "/getUser/" + userId, // 正确路径：/sysUser/getUser/123
                type: "GET", // 查询接口通常用GET方法
                success: function(user) { // user为后端返回的用户对象
                    if (user) {
                        // 填充编辑表单
                        $("#editUserId").val(user.userId);
                        $("#editUserName").val(user.userName);
                        $("#editPid").val(user.pid || "");
                        $("#editEmail").val(user.email || "");
                        $("#editMobile").val(user.mobile || "");
                        $("#editAddress").val(user.address || "");
                        openModal("editModal");
                    } else {
                        alert("未找到该用户");
                    }
                },
                error: function(err) {
                    alert("获取用户信息失败：" + err.responseText);
                },
                complete: function() {
                    hideLoading();
                }
            });
        });

        // 关闭编辑模态框
        $("#closeEditModal, #cancelEdit").click(function() {
            closeModal("editModal");
        });

        // 保存编辑用户
        $("#saveEditUser").click(function() {
            if (!validateEditForm()) return;

            const user = {
                userId: parseInt($("#editUserId").val()), // 确保为数字类型
                userName: $("#editUserName").val().trim(),
                pid: $("#editPid").val().trim() || null,
                email: $("#editEmail").val().trim() || null,
                mobile: $("#editMobile").val().trim() || null,
                address: $("#editAddress").val().trim() || null,
                password: $("#editPassword").val().trim() // 密码非必填，后端可处理为空
            };

            showLoading();
            // 调用修改接口
            $.ajax({
                url: baseUrl + "/updateUser",
                type: "PUT",
                contentType: "application/json",
                data: JSON.stringify(user),
                success: function(res) {
                    if (res === "success") {
                        alert("修改成功！");
                        closeModal("editModal");
                        loadUsers();
                    } else {
                        alert("修改失败！");
                    }
                },
                error: function(err) {
                    alert("服务器错误：" + err.responseText);
                },
                complete: function() {
                    hideLoading();
                }
            });
        });

        // 删除按钮点击事件（事件委托）
        $("#userTable").on("click", ".delete", function() {
            const userId = $(this).data("id");
            $("#deleteUserId").val(userId);
            openModal("deleteModal");
        });

        // 关闭删除模态框
        $("#closeDeleteModal, #cancelDelete").click(function() {
            closeModal("deleteModal");
        });

        // 确认删除
        $("#confirmDelete").click(function() {
            const userId = $("#deleteUserId").val();
            showLoading();

            // 调用删除接口
            $.ajax({
                url: baseUrl + "/delUser/" + userId,
                type: "DELETE",
                success: function(res) {
                    if (res === "success") {
                        alert("删除成功！");
                        closeModal("deleteModal");
                        loadUsers();
                    } else {
                        alert("删除失败！");
                    }
                },
                error: function(err) {
                    alert("服务器错误：" + err.responseText);
                },
                complete: function() {
                    hideLoading();
                }
            });
        });
    });

    // 加载用户列表（支持搜索）
    function loadUsers(searchName = "") {
        let url = "";
        if (searchName) {
            url = baseUrl + "/search?userName=" + encodeURIComponent(searchName);
        } else {
            url = baseUrl + "/getAllUsers";
        }

        $.ajax({
            url: url,
            type: "GET",
            success: function(users) {
                renderUserTable(users);
            },
            error: function(err) {
                alert("获取用户列表失败：" + err.responseText);
                renderUserTable([]);
            }
        });
    }

    // 渲染用户表格
    function renderUserTable(users) {
        const tbody = $("#userTable tbody");
        tbody.empty();

        if (users.length === 0) {
            tbody.append(`
                <tr>
                    <td colspan="7" class="empty-data">
                        <p>暂无用户数据</p>
                    </td>
                </tr>
            `);
            return;
        }

        users.forEach(function(user) {
            const row = `
                <tr>
                    <td>${user.userId}</td>
                    <td>${user.userName}</td>
                    <td>${user.pid || ""}</td>
                    <td>${user.email || ""}</td>
                    <td>${user.mobile || ""}</td>
                    <td>${user.address || ""}</td>
                    <td>
                        <button class="operate-btn edit" data-id="${user.userId}">修改</button>
                        <button class="operate-btn delete" data-id="${user.userId}">删除</button>
                    </td>
                </tr>
            `;
            tbody.append(row);
        });
    }

    // 打开模态框
    function openModal(modalId) {
        $(`#${modalId}`).css("display", "flex");
    }

    // 关闭模态框
    function closeModal(modalId) {
        $(`#${modalId}`).css("display", "none");
    }

    // 重置添加用户表单
    function resetAddForm() {
        $("#addUserName").val("");
        $("#addPid").val("");
        $("#addEmail").val("");
        $("#addMobile").val("");
        $("#addAddress").val("");
        $("#addPassword").val("");
    }

    // 显示加载动画
    function showLoading() {
        $("#loading").css("display", "flex");
    }

    // 隐藏加载动画
    function hideLoading() {
        $("#loading").css("display", "none");
    }

    // 添加表单验证
    function validateAddForm() {
        const userName = $("#addUserName").val().trim();
        const email = $("#addEmail").val().trim();
        const mobile = $("#addMobile").val().trim();
        const password = $("#addPassword").val().trim();

        if (!userName) {
            alert("请输入用户名");
            return false;
        }

        if (email && !validateEmail(email)) {
            alert("请输入有效的邮箱地址");
            return false;
        }

        if (mobile && !validateMobile(mobile)) {
            alert("请输入有效的手机号码");
            return false;
        }

        if (!password) {
            alert("请输入密码");
            return false;
        }

        return true;
    }

    // 编辑表单验证
    function validateEditForm() {
        const userName = $("#editUserName").val().trim();
        const email = $("#editEmail").val().trim();
        const mobile = $("#editMobile").val().trim();

        if (!userName) {
            alert("请输入用户名");
            return false;
        }

        if (email && !validateEmail(email)) {
            alert("请输入有效的邮箱地址");
            return false;
        }

        if (mobile && !validateMobile(mobile)) {
            alert("请输入有效的手机号码");
            return false;
        }

        return true;
    }

    // 邮箱验证
    function validateEmail(email) {
        const re = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
        return re.test(email);
    }

    // 手机号验证
    function validateMobile(mobile) {
        const re = /^1[3456789]\d{9}$/;
        return re.test(mobile);
    }
</script>

</script>
</body>
</html>
